import React, { useState, useEffect } from 'react';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import Box from '@mui/material/Box';
import ConnectionPanel from './components/ConnectionPanel';
import TerminalPanel from './components/TerminalPanel';

// 创建主题
const darkTheme = createTheme({
  palette: {
    mode: 'dark',
    primary: {
      main: '#90caf9',
    },
    secondary: {
      main: '#f48fb1',
    },
  },
});

const lightTheme = createTheme({
  palette: {
    mode: 'light',
    primary: {
      main: '#1976d2',
    },
    secondary: {
      main: '#e91e63',
    },
  },
});

function App() {
  // 状态管理
  const [darkMode, setDarkMode] = useState(true);
  const [connections, setConnections] = useState([]);
  const [activeConnections, setActiveConnections] = useState([]); // 存储所有活动连接ID数组
  
  // 加载保存的连接
  useEffect(() => {
    if (window.electron) {
      // 请求加载保存的连接
      window.electron.ipcRenderer.send('load-connections');
      
      // 监听加载的连接数据
      const handleConnectionsLoaded = (event, loadedConnections) => {
        if (Array.isArray(loadedConnections)) {
          console.log('加载了保存的连接:', loadedConnections.length);
          setConnections(loadedConnections);
        }
      };
      
      window.electron.ipcRenderer.on('connections-loaded', handleConnectionsLoaded);
      
      return () => {
        window.electron.ipcRenderer.removeListener('connections-loaded', handleConnectionsLoaded);
      };
    }
  }, []);
  
  // 添加新连接
  const addConnection = (connection, shouldSave = false) => {
    const newConnection = {
      ...connection,
      id: connection.id || `conn-${Date.now()}`,
      // 如果是连接类型，设置状态为断开；如果是分组类型，不设置状态
      ...(connection.type !== 'group' ? { status: 'disconnected' } : {})
    };
    
    const updatedConnections = [...connections, newConnection];
    setConnections(updatedConnections);
    
    // 如果需要保存，则发送到主进程保存
    if (shouldSave) {
      saveConnections(updatedConnections);
    }
    
    return newConnection.id;
  };
  
  // 删除连接或分组
  const deleteConnection = (connectionId, shouldSave = true) => {
    // 递归查找所有子项ID
    const findAllChildrenIds = (parentId) => {
      const children = connections.filter(conn => conn.parentId === parentId);
      let ids = [parentId];
      
      children.forEach(child => {
        ids = [...ids, ...findAllChildrenIds(child.id)];
      });
      
      return ids;
    };
    
    // 获取要删除的所有ID（包括子项）
    const idsToDelete = findAllChildrenIds(connectionId);
    
    // 过滤掉要删除的连接
    const updatedConnections = connections.filter(conn => !idsToDelete.includes(conn.id));
    setConnections(updatedConnections);
    
    // 从活动连接数组中移除被删除的连接
    setActiveConnections(prev => prev.filter(id => !idsToDelete.includes(id)));
    
    // 如果需要保存，则发送到主进程保存
    if (shouldSave) {
      saveConnections(updatedConnections);
    }
  };
  
  // 更新连接或分组
  const updateConnection = (updatedConnection, shouldSave = true) => {
    const updatedConnections = connections.map(conn => 
      conn.id === updatedConnection.id ? { ...conn, ...updatedConnection } : conn
    );
    
    setConnections(updatedConnections);
    
    // 如果需要保存，则发送到主进程保存
    if (shouldSave) {
      saveConnections(updatedConnections);
    }
  };
  
  // 重命名分组
  const renameGroup = (groupId, newName, shouldSave = true) => {
    const updatedConnections = connections.map(conn => 
      conn.id === groupId ? { ...conn, name: newName } : conn
    );
    
    setConnections(updatedConnections);
    
    // 如果需要保存，则发送到主进程保存
    if (shouldSave) {
      saveConnections(updatedConnections);
    }
  };
  
  // 保存连接到主进程
  const saveConnections = (connectionsToSave) => {
    // 过滤掉临时连接和状态信息，只保存配置
    const dataToSave = connectionsToSave
      .filter(conn => !conn.temp)
      .map(conn => {
        // 如果是分组类型，只保存必要的分组信息
        if (conn.type === 'group') {
          return {
            id: conn.id,
            name: conn.name,
            type: 'group',
            parentId: conn.parentId
          };
        }
        
        // 如果是连接类型，保存完整的连接信息
        return {
          id: conn.id,
          host: conn.host,
          port: conn.port,
          username: conn.username,
          authType: conn.authType,
          password: conn.authType === 'password' ? conn.password : '',
          privateKey: conn.authType === 'privateKey' ? conn.privateKey : '',
          type: conn.type || 'connection',
          parentId: conn.parentId || conn.group // 支持 group 字段作为 parentId
        };
      });
    
    window.electron.ipcRenderer.send('save-connections', dataToSave);
  };
  
  // 连接到服务器
  const connectToServer = (connectionId) => {
    const connection = connections.find(conn => conn.id === connectionId);
    if (connection) {
      // 通过IPC发送连接请求到主进程
      window.electron.ipcRenderer.send('ssh-connect', connection);
      
      // 更新连接状态为连接中
      setConnections(connections.map(conn => 
        conn.id === connectionId ? { ...conn, status: 'connecting' } : conn
      ));
      
      // 添加到活动连接数组（如果不存在）
      if (!activeConnections.includes(connectionId)) {
        setActiveConnections(prev => [...prev, connectionId]);
      }
    }
  };
  
  // 断开连接
  const disconnectFromServer = (connectionId) => {
    window.electron.ipcRenderer.send('ssh-disconnect', { connectionId });
    
    // 从活动连接数组中移除
    setActiveConnections(prev => prev.filter(id => id !== connectionId));
  };
  
  // 发送命令到终端
  const sendCommand = (command, connectionId) => {
    console.log('发送命令到SSH:', command, '连接ID:', connectionId);
    if (connectionId) {
      window.electron.ipcRenderer.send('ssh-data', {
        connectionId: connectionId,
        input: command
      });
    } else {
      console.warn('未指定连接ID，无法发送命令');
    }
  };
  
  // 监听SSH状态更新
  useEffect(() => {
    if (window.electron) {
      // 处理SSH状态更新
      const handleSshStatus = (event, data) => {
        // 添加数据验证，防止解构undefined
        if (!data) {
          console.error("SSH状态更新收到undefined数据");
          return;
        }

        const { connectionId, status, message } = data;
        // console.log("解构后的数据:", { connectionId, status, message });
        
        // 更新连接状态
        setConnections(prevConnections => 
          prevConnections.map(conn => 
            conn.id === connectionId ? { ...conn, status, errorMessage: message } : conn
          )
        );
        
        // 如果连接断开，从活动连接数组中移除
        if (status === 'disconnected') {
          setActiveConnections(prev => prev.filter(id => id !== connectionId));
        }
      };
      
      // 处理SSH数据
      const handleSshData = (event, data) => {
        if (!data) {
          console.error("SSH数据接收到undefined数据");
          return;
        }
        
        // console.log("收到SSH数据:", data);
        // 这里不需要做任何处理，TerminalPanel会直接监听这个事件
      };
      
      // 添加监听器
      window.electron.ipcRenderer.on('ssh-status', handleSshStatus);
      window.electron.ipcRenderer.on('ssh-data', handleSshData);
      
      // 清理函数
      return () => {
        window.electron.ipcRenderer.removeListener('ssh-status', handleSshStatus);
        window.electron.ipcRenderer.removeListener('ssh-data', handleSshData);
      };
    }
  }, []);
  
  return (
    <ThemeProvider theme={darkMode ? darkTheme : lightTheme}>
      <CssBaseline />
      <Box sx={{ display: 'flex', flexDirection: 'column', height: '100vh' }}>
        <Box sx={{ display: 'flex', flexGrow: 1, overflow: 'hidden' }}>
          <ConnectionPanel 
            connections={connections} 
            addConnection={addConnection}
            deleteConnection={deleteConnection}
            updateConnection={updateConnection}
            renameGroup={renameGroup}
            connectToServer={connectToServer}
            disconnectFromServer={disconnectFromServer}
            activeConnections={activeConnections}
          />
          <TerminalPanel 
            activeConnections={activeConnections.map(id => connections.find(conn => conn.id === id)).filter(Boolean)}
            connections={connections}
            sendCommand={sendCommand}
          />
        </Box>
      </Box>
    </ThemeProvider>
  );
}

export default App;